package admin

import (
	"gitee.com/jikey/elk-blog/app/model"
	"gitee.com/jikey/elk-blog/app/service"
	"gitee.com/jikey/elk-blog/middleware"
	"gitee.com/jikey/elk-blog/pkg/e"
	"gitee.com/jikey/elk-blog/pkg/response"
	"github.com/gin-gonic/gin"
	jwtgo "github.com/golang-jwt/jwt/v4"
	_ "github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
	"net/url"
	"strings"
	"time"
)

type Auth struct{}

// Login 登录
func (_ *Auth) Login(c *gin.Context) {
	response.HTML(c, "auth/login", nil)
}

// SignIn 登录
func (_ *Auth) SignIn(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	// todo 验证数据有效性

	user, errCode := service.User.SignIn(username, password)

	if errCode == 0 {
		generateToken(c, user)
	} else {
		response.Fail(c, e.AuthUserPasswordError)
	}
}

// SignUp 注册
func (_ *Auth) SignUp(c *gin.Context) {
	userModel := &model.User{}

	if err := c.ShouldBindJSON(&userModel); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	err := service.User.Create(userModel)

	if err != nil {
		logrus.Error("注册失败: ", err)
		return
	}

	response.Success(c, userModel, e.AuthSignInSuccess)
}

// redirectUrl 跳转url
func redirectUrl(c *gin.Context) (redirectUrl string) {
	referer := c.Request.Referer()
	isLogin, _ := checkSameUrl(referer)

	if isLogin {
		redirectUrl = "/"
		return
	}

	redirectUrl = referer
	return
}

// 检查是否同一页面
func checkSameUrl(location string) (res bool, err error) {
	urlInfo, err := url.Parse(location)
	if err != nil {
		return
	}

	path := urlInfo.Path
	if strings.Index(location, path) != -1 {
		res = true
	}
	res = false

	return
}

// generateToken 生成token
func generateToken(c *gin.Context, user *model.User) {
	data := map[string]interface{}{}
	now := time.Now()

	j := middleware.NewJWT()
	claims := middleware.JWTCustomClaims{
		UserID:   cast.ToString(user.Id),
		Username: user.Username,
		RegisteredClaims: jwtgo.RegisteredClaims{
			IssuedAt:  jwtgo.NewNumericDate(now),                                               // 签发时间
			ExpiresAt: jwtgo.NewNumericDate(time.Now().Add(12 * time.Hour * time.Duration(1))), // 过期时间12小时
		},
	}

	token, err := j.CreateToken(claims)

	if err != nil {
		logrus.Error(err)
		response.Fail(c, e.AuthFailedGenerateToken)
		return
	}

	user.Password = ""
	data["user"] = user
	data["token"] = token

	response.Success(c, data, e.AuthLoginSuccess)
}
